import os
import sys
# DON'T CHANGE THIS !!!
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from flask import Flask, send_from_directory, jsonify
from flask_cors import CORS
from src.models.user import db
from src.routes.auth import auth_bp
from src.routes.circle import circle_bp
from src.routes.location import location_bp
from src.routes.message import message_bp

app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'static'))
app.config['SECRET_KEY'] = 'asdf#FGSgvasgf$5$WGT'

# 启用CORS支持
CORS(app, origins="*")

# 注册蓝图
app.register_blueprint(auth_bp, url_prefix='/api/auth')
app.register_blueprint(circle_bp, url_prefix='/api/circles')
app.register_blueprint(location_bp, url_prefix='/api/locations')
app.register_blueprint(message_bp, url_prefix='/api/messages')

# 数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(__file__), 'database', 'app.db')}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# 创建数据库表
with app.app_context():
    db.create_all()

# API文档路由
@app.route('/api/docs')
def api_docs():
    """API文档"""
    docs = {
        "title": "WalkerRadio API Documentation",
        "version": "1.0.0",
        "description": "户外电波应用后端API接口文档",
        "endpoints": {
            "认证相关": {
                "POST /api/auth/send-code": "发送验证码",
                "POST /api/auth/login": "登录/注册",
                "GET /api/auth/profile/<user_id>": "获取用户资料",
                "PUT /api/auth/profile/<user_id>": "更新用户资料"
            },
            "圈子管理": {
                "POST /api/circles/circles": "创建圈子",
                "GET /api/circles/circles/<circle_id>": "获取圈子详情",
                "POST /api/circles/circles/join": "加入圈子",
                "POST /api/circles/circles/<circle_id>/leave": "退出圈子",
                "POST /api/circles/circles/<circle_id>/kick": "踢出成员",
                "POST /api/circles/circles/<circle_id>/dissolve": "解散圈子",
                "GET /api/circles/users/<user_id>/circles": "获取用户圈子列表"
            },
            "位置共享": {
                "POST /api/locations/locations": "更新位置",
                "GET /api/locations/circles/<circle_id>/locations": "获取圈子位置",
                "GET /api/locations/users/<user_id>/locations": "获取用户位置历史",
                "GET /api/locations/circles/<circle_id>/online-members": "获取在线成员"
            },
            "消息聊天": {
                "POST /api/messages/messages": "发送消息",
                "GET /api/messages/circles/<circle_id>/messages": "获取消息历史",
                "GET /api/messages/circles/<circle_id>/messages/recent": "获取最近消息",
                "DELETE /api/messages/messages/<message_id>": "删除消息",
                "GET /api/messages/circles/<circle_id>/messages/voice": "获取语音消息"
            }
        }
    }
    return jsonify(docs)

# 健康检查
@app.route('/api/health')
def health_check():
    """健康检查"""
    return jsonify({
        "status": "healthy",
        "service": "WalkerRadio Backend",
        "version": "1.0.0"
    })

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    static_folder_path = app.static_folder
    if static_folder_path is None:
            return "Static folder not configured", 404

    if path != "" and os.path.exists(os.path.join(static_folder_path, path)):
        return send_from_directory(static_folder_path, path)
    else:
        index_path = os.path.join(static_folder_path, 'index.html')
        if os.path.exists(index_path):
            return send_from_directory(static_folder_path, 'index.html')
        else:
            return "index.html not found", 404

# 错误处理
@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': '资源未找到'}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'error': '服务器内部错误'}), 500

if __name__ == '__main__':
    # 创建数据库表
    with app.app_context():
        db.create_all()
        print("数据库表已创建")
    
    app.run(host='0.0.0.0', port=5000, debug=True)

